package oj;

//删除元素
public class Num203 {
    public static void main(String[] args) {
        System.out.println();
    }

    public ListNode removeElements(ListNode head, int val) {
        while (head != null && head.val == val) {
            ListNode node = head;
            head = node.next;
            node.next = null;
        }
        if (head == null) {
            return null;
        } else {
            ListNode prev = head;
            while (prev.next != null) {
                if (prev.next.val == val) {
                    ListNode node = prev.next;
                    prev.next = node.next;
                    node.next = null;
                } else {
                    prev = prev.next;
                }
            }
        }
        return head;
    }
    //虚拟头节点    (不需要专门删除头节点的逻辑操作)
    public ListNode removeElements2(ListNode head, int val){
        ListNode firstNode = new ListNode();
        firstNode.next = head;


        ListNode prev = firstNode;
        ListNode node = firstNode.next;

        while (node != null){
            if(node.val == val){
                node = node.next;
                prev.next = node;
            }else {
                prev = node;
                node = node.next;
            }
        }
        return firstNode.next;
    }

    //链表其实是天然的递归结构，删除所有元素这个问题能否用递归来解决？
    public ListNode recursionRemoveElements(ListNode head, int val) {
        if (head == null) {
            return head;
        }
        head.next = recursionRemoveElements(head.next, val);
        return head.val == val ? head.next : head;
    }
}
